package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.MyBaseContext;
import com.itheima.reggie.common.MyException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


@Service
@Transactional
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;


    @Override
    public R submit(Orders orders) {
        Long id = MyBaseContext.getId();
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, id);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(lqw);
        if (null == shoppingCarts && shoppingCarts.size() == 0) {
            throw new MyException("购物车为空，下单失败");
        }
        User user = userService.getById(id);

        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (null == addressBook) {
            throw new MyException("地址有误，下单失败");
        }
        Long id1 = IdWorker.getId();
        AtomicInteger atom = new AtomicInteger(0);
        List<OrderDetail> list = new ArrayList<>();

        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail= new OrderDetail();
            orderDetail.setOrderId(id1);
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            atom.addAndGet(
                    shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue()
            );
            list.add(orderDetail);
        });


        orders.setId(id1);
        orders.setNumber(String.valueOf(id1));
        orders.setUserId(id);
        orders.setStatus(2);
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail())

        );
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setOrderTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(atom.get()));

        save(orders);


        orderDetailService.saveBatch(list);

        shoppingCartService.remove(lqw);

        return R.success("支付成功");
    }
}
